import { createAnimate } from "./animate.js";

function $(selector) {
    return document.querySelector(selector)
}

const doms = {
    container: $('.carousel-container'),
    carsouselList: $('.carousel-list'),
    indicator: $(".indicator"),
    arrowLeft: $('.arrow-left'),
    arrowRight: $('.arrow-right'),
}

const urls = [
    './imgs/img1.png',
    './imgs/img2.png',
    './imgs/img3.png',
    './imgs/img4.png',
    './imgs/img5.png',
];
let currentIndex = 0;
let containerWidth = doms.container.clientWidth;
let totalMS = 300;
let isPlaying = false;


function init() {
    function _createImg(url) {
        let img = document.createElement('img');
        img.className = 'carousel-item';
        img.src = url;
        doms.carsouselList.appendChild(img);
    }

    for (let i = 0; i < urls.length; i++) {
        let url = urls[i]
        _createImg(url);
        let div = document.createElement('div');
        div.className = 'indicator-item';
        doms.indicator.appendChild(div);
    }
    _createImg(urls[0])
    doms.carsouselList.style.width = `${doms.carsouselList.children.length}00%`;

    setIndicatorStatus();
    for (let i = 0; i < doms.indicator.children.length; i++) {
        doms.indicator.children[i].onclick = function () {
            moveTo(i)
            setIndicatorStatus();
        }
    }
}

function setIndicatorStatus() {
    let active = $('.indicator-item.active');
    if (active) {
        active.classList.remove('active');
    }
    let index = currentIndex % doms.indicator.children.length;
    doms.indicator.children[index].classList.add('active');
}

function moveTo(newIndex, onend) {
    if (isPlaying || currentIndex === newIndex) return;
    isPlaying = true;
    let from = parseFloat(doms.carsouselList.style.marginLeft) || 0;
    let to = -newIndex * containerWidth;
    createAnimate({
        from,
        to,
        totalMS,
        onMove: function (n) {
            // console.log(n)
            doms.carsouselList.style.marginLeft = n + 'px';
        },
        onEnd: function () {
            isPlaying = false;
            onend && onend();
        }
    })
    currentIndex = newIndex;
    setIndicatorStatus();
}

function next() {
    let newIndex = currentIndex + 1;
    let onend;
    if (newIndex === doms.carsouselList.children.length - 1) {
        onend = function () {
            requestAnimationFrame(() => {
                doms.carsouselList.style.marginLeft = '0px';
                console.log('执行了', doms.carsouselList.style.marginLeft)
                currentIndex = 0;
            })

        }
    }
    moveTo(newIndex, onend);
}

function prev() {
    let newIndex = currentIndex - 1;
    if (newIndex < 0) {
        let maxIndex = doms.carsouselList.children.length - 1;
        doms.carsouselList.style.marginLeft = -maxIndex * containerWidth + 'px';
        newIndex = maxIndex - 1;
    }
    moveTo(newIndex);
}



init();
doms.arrowLeft.onclick = prev;
doms.arrowRight.onclick = next;